package com.qst.itoffer.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;


@Controller
@RequestMapping
public class ValidateCodeController {
    private static final int WIDTH = 120;    // 验证码图片宽度
    private static final int HEIGHT = 40;    // 验证码图片高度
    private static final int CODE_COUNT = 4; // 验证码字符个数
    private static final int LINE_COUNT = 20; // 干扰线数量

    @GetMapping("/validateCode")
    public void validateCode(HttpServletRequest request,
                             HttpServletResponse response) throws IOException, IOException {
        // 设置响应头
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        // 创建内存图像
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();

        // 1. 绘制背景
        g.setColor(getRandomColor(200, 250));
        g.fillRect(0, 0, WIDTH, HEIGHT);

        // 2. 绘制干扰线
        Random random = new Random();
        g.setColor(getRandomColor(160, 200));
        for (int i = 0; i < LINE_COUNT; i++) {
            int x = random.nextInt(WIDTH);
            int y = random.nextInt(HEIGHT);
            int xl = random.nextInt(12);
            int yl = random.nextInt(12);
            g.drawLine(x, y, x + xl, y + yl);
        }

        // 3. 生成随机验证码
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < CODE_COUNT; i++) {
            String rand = String.valueOf(random.nextInt(10));
            sb.append(rand);
            g.setColor(new Color(20 + random.nextInt(110),
                    20 + random.nextInt(110),
                    20 + random.nextInt(110)));
            g.setFont(new Font("Arial", Font.BOLD, 24));
            g.drawString(rand, 24 * i + 10, 28);
        }

        // 4. 将验证码存入session
        request.getSession().setAttribute("validateCode", sb.toString());

        // 5. 输出图像
        g.dispose();
        ImageIO.write(image, "JPEG", response.getOutputStream());
    }

    // 生成随机颜色
    private Color getRandomColor(int fc, int bc) {
        Random random = new Random();
        if (fc > 255) fc = 255;
        if (bc > 255) bc = 255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }
}
